package com.third.bank.util;

import com.third.bank.entity.Staff;
import com.third.bank.entity.User;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

/**
 * jwt工具类
 */
public class JwtUtil {
//  签名的key
    private static final String SECRET_KEY = "bank";
//    token有效期
    private static final long EXPIRATION_TIME = 1000 * 60 * 60 * 24;

    /**
     * 生成一个token
     * @return
     */
    public static String createToken(User user){
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                .claim("id",user.getId())
                .claim("username",user.getUsername())
                .claim("id_card",user.getIdCard())
                .setSubject("loginUser")
                .setExpiration(new Date(System.currentTimeMillis()+ EXPIRATION_TIME))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256,SECRET_KEY)
                .compact();

        return jwtToken;
    }

    /**
     * 生成一个token
     * @return
     */
    public static String createToken(Staff staff){
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                .claim("id",staff.getId())
                .claim("staffAccount",staff.getStaffAccount())
                .claim("staffName",staff.getStaffName())
                .setSubject("loginStaff")
                .setExpiration(new Date(System.currentTimeMillis()+ EXPIRATION_TIME))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256,SECRET_KEY)
                .compact();

        return jwtToken;
    }

    /**
     * 解析token,获取id_card
     */
    public static String parse(String token){
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(SECRET_KEY).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return claims.get("id_card").toString();
    }

    /**
     * 解析token,获取id
     */
    public static String parseGetId(String token){
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(SECRET_KEY).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return claims.get("id").toString();
    }

    /**
     * 检测是否存在token
     * @param token
     * @return
     */
    public static boolean checkToken(String token){
        if (token == null){
            return false;
        }
        try{
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 获取过期时间
     * @param token
     * @return
     */
    public static Date getExpirationTime(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
            return claims.getExpiration();
        } catch (Exception e) {
            throw new JwtException("Invalid token", e);
        }
    }

    /**
     * 刷新过期时间
     * @param token
     * @param lastAccessedTime
     * @return
     */
    public static String refreshExpirationTime(String token, Date lastAccessedTime) {
        // 从Token中获取Claims
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();

        // 构建新的Token
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setClaims(claims)  // 将原Token中的Claims复制到新的Token中
                .setExpiration(lastAccessedTime)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY);

        // 返回新的Token
        return builder.compact();
    }


}
